﻿<%@ WebHandler Language="C#" Class="attendanceManage" %>

using System;
using System.Web;
using Chenxin.Lib.Hr.Entity;
using Chenxin.Lib.Utility;

public class attendanceManage : AjaxHandlerBase{

    //*******************************************
    //功能概要       ：重写的请求处理方法
    //参数説明       ：context 请求的上下文
    //返回值説明     ：无
    //功能詳細       ：父类中隐藏了IHttpHandler接口方法，本类中须对本方法进行重写
    //作成者         ：he.jifeng 
    //作成日         ：2010-03-18 
    //*******************************************
    override public void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        
        //处理类型
        string strDealType  = context.Request.Params["op"];

        switch (strDealType)
        {
            case "AddStartWork":
                addAttendance(context,"Start");
                break;
            case "AddEndWork":
                addAttendance(context, "End");
                break;
            case "Search":
                searchInfo(context);
                break;
            case "GetDeparts":
                getDeparts(context);
                break;
        }
    }

    //*******************************************
    //功能概要       ：添加上下班时间记录
    //参数説明       ：context:请求上下文
    //               ：strType:上下班区分
    //返回值説明     ：无
    //功能詳細       ：添加上下班时间记录
    //作成者         ：he.jifeng 
    //作成日         ：2010-03-18 
    //*******************************************
    private void addAttendance(HttpContext context, string strType)
    {
        try
        {
            //考勤记录实体
            Chenxin.Lib.Hr.Entity.Hr_AttendanceRecord entAttendanceRec = new Chenxin.Lib.Hr.Entity.Hr_AttendanceRecord();
            //考勤业务类
            Chenxin.Lib.Hr.BLL.Hr_AttendanceRecord bllAttendanceRec = new Chenxin.Lib.Hr.BLL.Hr_AttendanceRecord();
            //考勤周期业务类
            Chenxin.Lib.Hr.BLL.Struct_AttendanceCircle bllAttendanceCir = new Chenxin.Lib.Hr.BLL.Struct_AttendanceCircle();
            //考勤周期实体类
            Chenxin.Lib.Hr.Entity.Struct_AttendanceCircle entAttendanceCir = bllAttendanceCir.GetModel();

            DateTime dtNow = DateTime.Now;

            entAttendanceRec.RecordId = Guid.NewGuid();
            entAttendanceRec.DepartId = CurrentUserInfo.DepartId;
            entAttendanceRec.UserId = CurrentUserInfo.UserId;
            entAttendanceRec.UserCode = CurrentUserInfo.UserCode;
            entAttendanceRec.Year = dtNow.Year.ToString();
            //开始月和结束月份相同
            if (entAttendanceCir.StartMonthFlg == entAttendanceCir.EndMonthFlg)
            {
                entAttendanceRec.Month = dtNow.Month.ToString().PadLeft(2, '0');    
            }
            else
            {
                //判断当前月份
                if (DateTime.Now.Day < entAttendanceCir.StartDate.Value)
                {
                    entAttendanceRec.Month = dtNow.Month.ToString().PadLeft(2, '0');
                }
                else
                {
                    entAttendanceRec.Month = (dtNow.Month + 1).ToString().PadLeft(2, '0');
                }
            }
            
            entAttendanceRec.DateTime = DateTime.Now;
            entAttendanceRec.Time = DateTime.Now.ToLongTimeString();

            //上班
            if (strType == "Start")
            {
                entAttendanceRec.Type = "S";
            }
            //下班
            else
            {
                entAttendanceRec.Type = "E";
            }

            //添加记录
            bllAttendanceRec.Add(entAttendanceRec);
            
            //响应内容
            context.Response.Write(Chenxin.Lib.Utility.JsonHelper<string>.WriteObject("SUCCESS", dtNow.ToShortTimeString()));
        }
        catch (Exception ex)
        {
            //错误信息回传
            context.Response.Write(Chenxin.Lib.Utility.JsonHelper<string>.WriteObject("ERROR", ex.Message));
        }
    }
    
    //*******************************************
    //功能概要       ：查找用户考勤信息
    //参数説明       ：context:请求上下文
    //返回值説明     ：无
    //功能詳細       ：查找用户考勤信息
    //作成者         ：he.jifeng 
    //作成日         ：2010-03-19
    //*******************************************
    private void searchInfo(HttpContext context)
    {
        try
        {
            //年月
            string strYearMonth = context.Request.Params["YearMonth"];
            //年份
            string strYear = string.Empty;
            //月份
            string strMonth = string.Empty;

            if (strYearMonth != null)
            {
                //年份
                strYear = strYearMonth.Substring(0, 4);
                //月份
                strMonth = strYearMonth.Substring(5, 2);
            }
            else
            {
                //年份
                strYear = DateTime.Now.Year.ToString().PadLeft(4, '0');
                //月份
                strMonth = DateTime.Now.Month.ToString().PadLeft(2, '0');
            }
            //人员条件列表
            System.Collections.Hashtable hsParamsAtt= new System.Collections.Hashtable();
            //勤务条件列表
            System.Collections.Hashtable hsParamsUser = new System.Collections.Hashtable();
            
            if (!string.IsNullOrEmpty(context.Request["userid"]))
            {
                hsParamsAtt.Add("UserId", context.Request["userid"]);
                hsParamsUser.Add("UserId", context.Request["userid"]);
            }
            else if (!string.IsNullOrEmpty(context.Request["departid"]))
            {
                hsParamsAtt.Add("DepartId", context.Request["departid"]);
                hsParamsUser.Add("DepartId", context.Request["departid"]);
            }
            else if (!string.IsNullOrEmpty(context.Request["areaid"]))
            {
                hsParamsAtt.Add("AreaId", context.Request["areaid"]);
                hsParamsUser.Add("AreaId", context.Request["areaid"]);
            }
            else if (!string.IsNullOrEmpty(context.Request["companyid"]))
            {
                hsParamsAtt.Add("CompanyId", context.Request["companyid"]);
                hsParamsUser.Add("CompanyId", context.Request["companyid"]);
            }
            else if (!string.IsNullOrEmpty(context.Request["cityid"]))
            {
                hsParamsAtt.Add("CityId", context.Request["cityid"]);
                hsParamsUser.Add("CityId", context.Request["cityid"]);
            }
                //默认搜索条件
            else
            {
                hsParamsAtt.Add("CompanyId", CurrentUserInfo.CompanyId.ToString());
                hsParamsUser.Add("CompanyId", CurrentUserInfo.CompanyId.ToString());
            }
            
            if( strYear !=null | strYear !="")
            {
                hsParamsAtt.Add("Year",strYear);
            }
            if( strMonth !=null | strMonth !="")
            {
                hsParamsAtt.Add("Month",strMonth);
            }

            //当前页数
            string  strParam = context.Request.Params["pageindex"];
            if (!string.IsNullOrEmpty(strParam))
            {
                hsParamsUser.Add("pageIndex", (int.Parse(strParam) + 1).ToString());
            }
            //总页数
            strParam = context.Request.Params["pagesize"];
            if (!string.IsNullOrEmpty(strParam))
            {
                hsParamsUser.Add("pageSize", strParam);
            }
            
            //权限判断
            //查看所有权限
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewAllAttendance))
            {
                hsParamsAtt.Add("Permit", Constants.Permit_ViewAllAttendance);
                hsParamsUser.Add("Permit", Constants.Permit_ViewAllAttendance);
            }
            //查看城市权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCityAttendance))
            {
                hsParamsAtt.Add("Permit", Constants.Permit_ViewCityAttendance);
                hsParamsAtt.Add("CurCityId", CurrentUserInfo.CityId.ToString());
                hsParamsUser.Add("Permit", Constants.Permit_ViewCityAttendance);
                hsParamsUser.Add("CurCityId", CurrentUserInfo.CityId.ToString());
                
            }
            //查看公司权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCompanyAttendance))
            {
                hsParamsAtt.Add("Permit", Constants.Permit_ViewCompanyAttendance);
                hsParamsAtt.Add("CurCompanyId", CurrentUserInfo.CompanyId.ToString());
                hsParamsUser.Add("Permit", Constants.Permit_ViewCompanyAttendance);
                hsParamsUser.Add("CurCompanyId", CurrentUserInfo.CompanyId.ToString());
            }
            //查看部门权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewDepartAttendance))
            {
                hsParamsAtt.Add("Permit", Constants.Permit_ViewDepartAttendance);
                hsParamsUser.Add("Permit", Constants.Permit_ViewDepartAttendance);
                hsParamsAtt.Add("CurUserId", CurrentUserInfo.UserId);
                hsParamsUser.Add("CurUserId", CurrentUserInfo.UserId);
            }
            //查看自己权限    
            else
            {
                hsParamsAtt.Add("CurUserId", CurrentUserInfo.UserId);
                hsParamsUser.Add("CurUserId", CurrentUserInfo.UserId);
            }
            
            //数据列表
            System.Text.StringBuilder strHtml = new System.Text.StringBuilder();
            
            //考勤记录业务类
            Chenxin.Lib.Hr.BLL.Hr_AttendanceRecord bllAttendanceRec = new Chenxin.Lib.Hr.BLL.Hr_AttendanceRecord();
            //员工业务类
            Chenxin.Lib.Passport.BLL.Hr_UserInfo bllUserInfo = new Chenxin.Lib.Passport.BLL.Hr_UserInfo();
            
            //考勤周期业务类
            Chenxin.Lib.Hr.BLL.Struct_AttendanceCircle bllAttendanceCir = new Chenxin.Lib.Hr.BLL.Struct_AttendanceCircle();
            //考勤周期实体类
            Chenxin.Lib.Hr.Entity.Struct_AttendanceCircle entAttendanceCir = bllAttendanceCir.GetModel();

            //用户列表
            //System.Collections.Generic.List<Chenxin.Lib.Passport.Entity.Hr_UserInfo> lsUserInfo = bllUserInfo.GetUserList(hsParamsUser);
            System.Data.DataSet dsUserInfo = bllUserInfo.GetUserList(hsParamsUser);

            //部门勤务信息
            System.Data.DataSet dsAttendanceRec = bllAttendanceRec.GetModelListByCoditions(hsParamsAtt);

            Constants.Pagination stuPag = new Constants.Pagination();
            
            //人员信息不为空
            if (dsUserInfo.Tables[0].Rows.Count > 0)
            {
                string strWhere;

                strHtml.Append("<table class='clsTbUser tabsorternew'>");
                //周期开始月的标识
                string strStartFlg = entAttendanceCir.StartMonthFlg;
                //周期结束月的标识
                string strEndFlg = entAttendanceCir.EndMonthFlg;
                //周期开始日
                int intStartDate = (int)entAttendanceCir.StartDate;
                DateTime dtStart;
                //周期结束日
                int intEndDate = (int)entAttendanceCir.EndDate;
                DateTime dtEnd;
                //当前月份
                //DateTime dtCurYearMonth = DateTime.Now;


                System.Data.DataRow[] drAttendance;
                DateTime dtAttendance;

                //假定周期开始日
                if (strStartFlg == "C")
                {
                    int intMonth = Convert.ToInt32(strMonth) - 1;
                    int intYear = Convert.ToInt32(strYear);
                    if (intMonth == 0)
                    {
                        intMonth = 12;
                        intYear = intYear - 1;
                    }
                    dtStart = new DateTime(intYear, intMonth, intStartDate);
                }
                else
                {
                    dtStart = new DateTime(Convert.ToInt32(strYear), Convert.ToInt32(strMonth), intStartDate);
                }
                //假定周期结束日
                dtEnd = new DateTime(Convert.ToInt32(strYear), Convert.ToInt32(strMonth), intEndDate);

                //第一行头
                strHtml.Append("<tr class='clsTrDate'>");
                strHtml.Append("<th rowspan=2 class='clsThUserNm scrollCR'>");
                strHtml.Append("</th>");
                //循环周期
                for (DateTime curDt = dtStart; curDt <= dtEnd; curDt = curDt.AddDays(1))
                {
                    strHtml.Append("<th colspan=2>");
                    strHtml.Append(curDt.ToLongDateString().Substring(5));
                    strHtml.Append("</th>");
                }
                strHtml.Append("</tr>");

                //第二行头
                strHtml.Append("<tr class='clsTrDate'>");
                for (DateTime curDt = dtStart; curDt <= dtEnd; curDt = curDt.AddDays(1))
                {
                    strHtml.Append("<th>上班</th>");
                    strHtml.Append("<th>下班</th>");
                }
                strHtml.Append("</tr>");

                //循环部门人员
                for (int idxCntOfUser = 0; idxCntOfUser < dsUserInfo.Tables[0].Rows.Count; idxCntOfUser++)
                {
                    strHtml.Append("<tr class='tr_houselist'>");
                    strHtml.Append("<th class='clsThUserNm'>");
                    strHtml.Append(dsUserInfo.Tables[0].Rows[idxCntOfUser]["UserName"]);
                    strHtml.Append("(" + dsUserInfo.Tables[0].Rows[idxCntOfUser]["UserCode"] + ")");
                    strHtml.Append("</th>");
                    for (DateTime curDt = dtStart; curDt <= dtEnd; curDt = curDt.AddDays(1))
                    {
                        strWhere = "UserId = '" + dsUserInfo.Tables[0].Rows[idxCntOfUser]["UserId"] + "'";
                        strWhere = strWhere + " And DateTime >= '" + curDt.ToShortDateString() + " 00:00:00'";
                        strWhere = strWhere + " And DateTime <= '" + curDt.ToShortDateString() + " 23:59:59'";
                        strWhere = strWhere + " And Type=";

                        drAttendance = dsAttendanceRec.Tables[0].Select(strWhere + "'S'");
                        if (drAttendance.Length > 0)
                        {
                            dtAttendance = (DateTime)drAttendance[0]["DateTime"];
                            //周末
                            if (curDt.DayOfWeek == DayOfWeek.Saturday | curDt.DayOfWeek == DayOfWeek.Sunday)
                            {
                                strHtml.Append("<td class='clsTdTime clsWeekEnd' style='white-space:nowrap'>");
                                strHtml.Append("<span>休假</span>");
                                strHtml.Append("<input type='hidden' name='hidStartTime' value='" + dtAttendance.ToShortTimeString() + "' />");
                            }
                            else
                            {

                                //迟到(大于9：00小于9：15)
                                if (dtAttendance.TimeOfDay > entAttendanceCir.StartTime.Value.TimeOfDay & dtAttendance.TimeOfDay < entAttendanceCir.LateTimeOut.Value.TimeOfDay)
                                {
                                    strHtml.Append("<td class='clsTdTime clsLate' style='white-space:nowrap'>");
                                }
                                //迟到超时
                                else if (dtAttendance.TimeOfDay > entAttendanceCir.LateTimeOut.Value.TimeOfDay)
                                {
                                    strHtml.Append("<td class='clsTdTime clsLateTimeOut' style='white-space:nowrap'>");
                                }
                                else
                                {
                                    strHtml.Append("<td class='clsTdTime' style='white-space:nowrap'>");
                                }
                                strHtml.Append(dtAttendance.ToShortTimeString());
                            }
                        }
                        else
                        {
                            //周末
                            if (curDt.DayOfWeek == DayOfWeek.Saturday | curDt.DayOfWeek == DayOfWeek.Sunday)
                            {
                                strHtml.Append("<td class='clsTdTime clsWeekEnd' style='white-space:nowrap'>");
                                strHtml.Append("<span>休假</span>");
                            }
                            else
                            {
                                strHtml.Append("<td class='clsTdTime' style='white-space:nowrap'>");
                            }
                        }
                        strHtml.Append("</td>");

                        drAttendance = dsAttendanceRec.Tables[0].Select(strWhere + "'E'");

                        if (drAttendance.Length > 0)
                        {
                            dtAttendance = (DateTime)drAttendance[0]["DateTime"];
                            //周末
                            if (curDt.DayOfWeek == DayOfWeek.Saturday | curDt.DayOfWeek == DayOfWeek.Sunday)
                            {
                                strHtml.Append("<td class='clsTdTime clsWeekEnd' style='white-space:nowrap'>");
                                strHtml.Append("<span>休假</span>");
                                strHtml.Append("<input type='hidden' name='hidStartTime' value='" + dtAttendance.ToShortTimeString() + "' />");
                            }
                            else
                            {
                                //早退
                                if (dtAttendance.TimeOfDay < entAttendanceCir.EndTime.Value.TimeOfDay)
                                {
                                    strHtml.Append("<td class='clsTdTime clsLeaveEarly' style='white-space:nowrap'>");
                                }
                                //加班
                                else if (dtAttendance.TimeOfDay > entAttendanceCir.OverTimeStartTime.Value.TimeOfDay)
                                {
                                    strHtml.Append("<td class='clsTdTime clsOverTime' style='white-space:nowrap'>");
                                }
                                else
                                {
                                    strHtml.Append("<td class='clsTdTime' style='white-space:nowrap'>");
                                }
                                strHtml.Append(dtAttendance.ToShortTimeString());
                            }
                        }
                        else
                        {
                            //周末
                            if (curDt.DayOfWeek == DayOfWeek.Saturday | curDt.DayOfWeek == DayOfWeek.Sunday)
                            {
                                strHtml.Append("<td class='clsTdTime clsWeekEnd' style='white-space:nowrap'>");
                                strHtml.Append("<span>休假</span>");
                            }
                            else
                            {
                                strHtml.Append("<td class='clsTdTime' style='white-space:nowrap'>");
                            }
                        }
                        strHtml.Append("</td>");

                    }
                    strHtml.Append("</tr>");
                }

                strHtml.Append("</table>");

                stuPag.data = strHtml.ToString();
                stuPag.count = Convert.ToInt32(dsUserInfo.Tables[1].Rows[0][0]);
                //响应内容
                context.Response.Write(retExecResult(Constants.ExecResult.Succ, "", stuPag));
            }
            else
            {
                stuPag.data = "";
                stuPag.count = 0;
                //响应内容
                context.Response.Write(retExecResult(Constants.ExecResult.Succ, "", stuPag));
            }
            
        }
        catch (Exception ex)
        {
            //错误信息回传
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }

    //*******************************************
    //功能概要       ：获得部门信息
    //参数説明       ：context:请求上下文
    //返回值説明     ：无
    //功能詳細       ：获得部门信息
    //作成者         ：he.jifeng 
    //作成日         ：2010-04-07
    //*******************************************
    public void getDeparts(HttpContext context)
    {
       //业务角色类
       Chenxin.Lib.Hr.BLL.Hr_DepartmentInfo bllHrDepartmentInfo = new Chenxin.Lib.Hr.BLL.Hr_DepartmentInfo();

       //json数据
       System.Text.StringBuilder strJson = new System.Text.StringBuilder();

       //部门列表取得
       System.Collections.Generic.List<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo> lsDeparts = bllHrDepartmentInfo.GetAllDeparts();

       //循环列表
       for (int idxCnt = 0; idxCnt < lsDeparts.Count; idxCnt++)
       {
           strJson.Append(",{ txt: '");
           strJson.Append(lsDeparts[idxCnt].DepartName);
           strJson.Append("', val: '");
           strJson.Append(lsDeparts[idxCnt].DepartId.ToString());
           strJson.Append("' }");
       }

       //strJson = "[" + strJson.Substring(1) + "]";
       context.Response.Write(strJson.ToString().Substring(1));
    }
}
